const fs = require('fs');
const path = require('path');

function readData(callback) {
    fs.readFile(path.join(__dirname, 'data', 'data.json'), (err, data) => {
        if (err) {
            return console.log('读取文件失败', err);
        }

        data = JSON.parse(data);
        // console.log(data);
        callback && callback(data);
    });
}


function writeData(newData, callback) {
    readData((data) => {
        newData.id = data.list[data.list.length - 1].id + 1;
        data.list.push(newData);

        console.log(data);


        data = JSON.stringify(data, null, 4);
        fs.writeFile(path.join(__dirname, 'data', 'data.json'), data, (err) => {
            if (err) {
                return console.log('写入文件失败', err);
            }
            callback && callback();
        });


    });
}
// writeData({ title: '我傻了', url: 'ddsa', text: '12' });

const tools = {
    readData,
    writeData
}

module.exports = tools;